public class MyBlockingQueue {
    String [] arr = new String[10];
    private int size = 0;
    private int head = 0;
    private int tail = 0;
    public void put(String str) throws InterruptedException {
        synchronized (this){
            //这里使用while而不使用if用来避免其他线程调用方法时，因为interrupt而将wait唤醒
            //若引interrupt将阻塞唤醒，那么此时队列还是满的，会丢失一个有效数据
            while(size == str.length()){
                this.wait();
            }
            arr[tail++] = str;
            if(tail == arr.length){
                tail = 0;
            }
            size++;
            this.notify();
        }
    }
    public String take() throws InterruptedException {
        String ret;
        synchronized (this){
            while (size == 0){
                this.wait();
            }
            ret = arr[head];
            if(head++ == arr.length){
                head = 0;
            }
            size--;
            this.notify();
        }
        return ret;
    }

    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue();
        //生产者
        Thread t1 = new Thread(()-> {
            int num = 1;
            while(true){
                try {
                    myBlockingQueue.put("" + num);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("生产者生产：" + num);
                num++;
            }
        });
        Thread t2 = new Thread(()-> {
            while(true) {
                String ret;
                try {
                    Thread.sleep(1000);
                    ret = myBlockingQueue.take();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("消费者消费：" + ret);
            }
        });
        t1.start();
        t2.start();
    }
}
